const db = require('../db/index');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')
const config = require('../confing')

exports.register = (req, res) => {
    const userinfo = req.body
    if (!userinfo.username || !userinfo.password) return res.status(400).json('用户名或密码不能为空')

    const sql = 'select * from userinfo where username = ?'
    db.query(sql, userinfo.username, (err, results) => {
        if(err) return res.status(400).json(err)
        if (results.length > 0 ) return res.status(401).json('用户名已存在，请使用新的用户名注册！')
        userinfo.password = bcrypt.hashSync(userinfo.password, 10)
        const registerSql = 'insert into userinfo set ?'
        db.query(registerSql, userinfo, (err, results) => {
            if(err) res.status(400).json(err)
            if(results.affectedRows !== 1) return res.status(400).json('注册失败')
            res.status(200).json('注册成功')
        })
    })
}

exports.login = (req, res) => {
    const userinfo = req.body
    const sql = 'select * from userinfo where username = ?'
    db.query(sql, userinfo.username, (err, results) => {
        if(err) return res.status(400).json(err)
        if(results.length !== 1) return res.status(400).json('用户不存在')

        const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
        if(!compareResult) return res.status(400).json('用户名或密码错误')

        const user = {
            id: results[0].id,
            username: results[0].username,
            // password: results[0].password
        }

        const tokenStr = jwt.sign(user, config.jwtSecretKey, {expiresIn: '10h'})
        res.json({
            status: 200,
            message: '登录成功',
            token: 'Bearer ' + tokenStr
        })
    })
}